<!-- 表格 -->
<table class="layui-hide" id="courseTable" lay-filter="courseTable"></table>
<!-- 表格工具 -->
<script type="text/html" id="toolbarCourse">
    <div class="layui-btn-container">
        <button class="layui-btn layui-btn-sm" lay-event="autoSortTest">自动排监考</button>
    </div>
</script>
<script type="text/html" id="courseSet">
    <a class="layui-btn layui-btn-xs" lay-event="sortTest">手工排监考</a>
</script>

<div class="margin-top30 J-auto-set-test is-hidden">
    <form class="layui-form layui-fluid" lay-filter="formTest">
        <div class="layui-form-item">
            <label class="layui-form-label">考试日期</label>
            <div class="layui-input-block">
                <input type="text" placeholder="请选择考试日期" autocomplete="off" readonly class="layui-input" id="taskDate" name="task_date" />
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">考试时间</label>
            <div class="layui-input-block">
                <input type="text" class="layui-input form-control-range" placeholder="开始时间" id="beginTime" name="begin_time" />
                <p class="col-sm-2 time-signal">~</p>
                <input type="text" class="layui-input form-control-range" placeholder="结束时间" id="endTime" name="end_time" />
            </div>
        </div>

        <!-- <div class="layui-form-item">
            <label class="layui-form-label">监考老师数:</label>
            <div class="layui-input-block">
                <select id="teacherNum" class="layui-input">
                    <option value="1">1名</option>
                    <option value="2">2名</option>
                </select>
            </div>
        </div> -->
    </form>
</div>

<script>
    var classData;
    function getTeacherIds() {
        var ids = [];
        for (let i = 0; i < teacherData.length; i++) {
            ids.push(Number(teacherData[i].teacherid));
        }
        return ids;
    }

    function initCourseTable() {
        layuiDate('.J-date');
        var table;
        // 请求路径
        var requireUrl = {
            courselist: "{:url('test/getcourselist')}",
            autoSortTest: "{:url('test/autoSortTest')}",
            getClassInfo: "{:url('test/getClassInfo')}",
        };
        initDate();
        ajaxRequest('get', requireUrl.getClassInfo, null, function (data) {
            console.log(data);
            classData = data;
        })

        layui.use('table', function () {
            table2 = layui.table;
            table2.render({
                elem: '#courseTable',
                url: requireUrl.courselist + '?ischeck=1',
                toolbar: '#toolbarCourse',
                title: '考试课程',
                totalRow: false,
                cols: [
                    [
                        { type: 'checkbox', fixed: 'left' },
                        { field: 'id', title: '序号', width: 60 },
                        { field: 'coursename', title: '课程', width: 100 },
                        {
                            field: 'c_type',
                            title: '课程类别',
                            width: 100,
                            templet: d => {
                                var result;
                                d.c_type == 0 && (result = '公共课');
                                d.c_type == 1 && (result = '专业核心课');
                                d.c_type == 2 && (result = '专业基础课');
                                return result;
                            },
                        },
                        { field: 'c_time', title: '课时', width: 50 },
                        {
                            field: 'c_test_type',
                            title: '考试形式',
                            width: 100,
                            templet: d => {
                                var result;
                                d.c_test_type == 10 && (result = '笔试(闭)');
                                d.c_test_type == 11 && (result = '笔试(开)');
                                d.c_test_type == 2 && (result = '上机');
                                d.c_test_type == 3 && (result = '大作业');
                                return result;
                            },
                        },
                        {
                            field: 'c_orange_type',
                            title: '组织形式',
                            templet: d => {
                                var result;
                                d.c_orange_type == 0 && (result = '<span class="">随堂考</span>');
                                d.c_orange_type == 1 && (result = '<span class="">统考</span>');
                                return result;
                            },
                        },
                        { field: 'name', title: '考试任务', width: 200 },
                        {
                            field: 'check',
                            title: '审核状态',
                            templet: d => {
                                var result;
                                d.check == 0 && (result = '<span class="">未审核</span>');
                                d.check == 1 && (result = '<span class="green">通过</span>');
                                d.check == 2 && (result = '<span class="red">不通过</span>');
                                return result;
                            },
                        },
                        // { field: 'demo', title: '备注', width: 200 },
                        // { field: 'create_time', title: '发布时间：', width: 200 },
                        // { fixed: 'right', title: '操作', toolbar: '#courseSet', minWidth: 120 },
                    ],
                ],
                id: 'courseTable',
                page: true,
                parseData: function (res) {
                    return {
                        code: 0,
                        msg: '',
                        count: res.length,
                        data: res,
                    };
                },
            });

            //工具栏事件
            table2.on('toolbar(courseTable)', function (obj) {
                var checkStatus = table2.checkStatus(obj.config.id);
                switch (obj.event) {
                    case 'autoSortTest':
                        // 手动排监考
                        console.log(checkStatus);
                        var data = checkStatus.data;
                        if (data.length == 0) {
                            layer.msg('请至少选择一条记录！', { icon: 7 });
                            return;
                        }

                        var list = [];
                        for (var i = 0; i < data.length; i++) {
                            list.push(data[i].kechengid);
                        }

                        layerOpenInit('自动排监考', $('.J-auto-set-test'), function (index) {
                            var courseIds = list;
                            var teacherIds = getTeacherIds();
                            // var teacherRanNum = RandomNumBoth(teacherIds, teacherIds.length);
                            console.log(teacherIds, 'teacherIds');
                            var parem = {};
                            var teacherIdCombination = [];

                            // var teacherSliceArrTo2 = sliceArrTo2(teacherRanNum);
                            // for (var d = 0; d < teacherSliceArrTo2[0].length; d++) {
                            //     for (var j = 0; j < teacherSliceArrTo2[1].length; j++) {
                            //         teacherIdCombination.push({
                            //             teacherId: teacherSliceArrTo2[0][d],
                            //             teacherId2: teacherSliceArrTo2[1][j],
                            //         });
                            //     }
                            // }

                            // teacherIdCombination = RandomNumBoth(teacherIdCombination, teacherIdCombination.length);
                            // teacherIdCombination = sliceArrTo2(teacherIdCombination);

                            var postRecords = function (callback, data) {
                                console.log(data, 'taskid');
                                data.schoolid = '985';
                                ajaxRequest('post', requireUrl.autoSortTest, data, function (data) {
                                    // data.code == 1 ? successTrip(data) : errorAlert(false, data.msg);
                                    callback && callback();
                                });
                            };

                            var courseNum = 0,
                                num = 0;

                            var autoSortTeacher2 = function () {
                                parem = {
                                    kechengid: courseIds[num],
                                    teacherid: teacherIdCombination[1][num].teacherId2,
                                    taskid: data[0].taskid,
                                };
                                postRecords(function () {
                                    num++;
                                    if (num < courseIds.length) {
                                        autoSortTeacher2();
                                    } else {
                                        successTrip({
                                            msg: '自动排监考成功',
                                            url: '',
                                        });
                                    }
                                }, parem);
                            };

                            var autoSortTeacher = function (num) {
                                if (courseNum < courseIds.length) {


                                    if ($('#teacherNum').val() == 1) {
                                        parem = {
                                            kechengid: courseIds[courseNum],
                                            teacherid: teacherIdCombination[0][courseNum].teacherId,
                                            taskid: data[0].taskid,
                                        };

                                        postRecords(function () {
                                            courseNum++;
                                            autoSortTeacher();
                                        }, parem);
                                    }

                                    if ($('#teacherNum').val() == 2) {
                                        parem = {
                                            kechengid: courseIds[courseNum],
                                            teacherid: teacherIdCombination[0][courseNum].teacherId,
                                            taskid: data[0].taskid,
                                        };

                                        postRecords(function () {
                                            courseNum++;
                                            //
                                            if (courseNum == courseIds.length) {
                                                autoSortTeacher2();
                                            } else {
                                                autoSortTeacher();
                                            }
                                        }, parem);
                                    }
                                } else {
                                    successTrip({
                                        msg: '自动排监考成功',
                                        url: '',
                                    });
                                }
                            };
                            // autoSortTeacher();

                            var hasRoomIds = new Array();
                            for (let i = 0; i < courseIds.length; i++) {
                                hasRoomIds[i] = new Array();
                                for (let j = 0; j < roomData.length; j++) {
                                    hasRoomIds[i][j] = new Array();
                                }
                            }

                            console.log(hasRoomIds);
                            var isHasRoomIds = function (id) {
                                for (let i = 0; i < hasRoomIds.length; i++) {
                                    try {
                                        for (let d = 0; d < hasRoomIds[i].length; d++) {
                                            if (id == hasRoomIds[i][d]) {
                                                return true;
                                            }
                                        }
                                    } catch (error) {}
                                }

                                return false;
                            }

                            for (let course = 0; course < courseIds.length; course++) {
                                for (let c = 0; c < classData.length; c++) {
                                    for (let i = 0; i < roomData.length; i++) {
                                        // debugger
                                        if (classData[c].number == roomData[i].test_capacity || classData[c].number < roomData[i].test_capacity) {
                                            if (isHasRoomIds(roomData[i].id)) {
                                                continue
                                            }
                                            console.log(roomData[i].id);
                                            hasRoomIds[course][c] = roomData[i].id;
                                            break;
                                        }
                                    }
                                }
                            }

                            console.log(hasRoomIds);

                            // return;

                            var postData = []
                            var teacherRanNum = []
                            for (var courseNum = 0; courseNum < courseIds.length; courseNum++) {
                                teacherRanNum = RandomNumBoth(getTeacherIds(), getTeacherIds().length);
                                for (var classNum = 0; classNum < classData.length; classNum++) {
                                    // if (classData[classNum].number == roomData[classNum].id)
                                    postData.push({
                                        schoolid: 985,
                                        kechengid: courseIds[courseNum],
                                        teacherid: teacherRanNum[classNum],
                                        taskid: data[0].taskid,
                                        class_id: classData[classNum].id,
                                        roomid: hasRoomIds[courseNum][classNum].length != 0 ? hasRoomIds[courseNum][classNum] : 1,
                                        task_date: $("#taskDate").val(),
                                        begin_time: $("#beginTime").val(),
                                        end_time: $("#endTime").val(),
                                    })

                                }

                            }
                            var resultList = {
                                resultList: JSON.stringify(postData)
                            }
                            console.log(postData);
                            // return


                            // }
                            ajaxRequest('post', requireUrl.autoSortTest, resultList, function (data) {
                                data.code == 1 ? successTrip(data) : errorAlert(false, data.msg);
                                // callback && callback();
                            });
                        });
                        break;
                }
            });

            //监听行工具事件
            table2.on('tool(courseTable)', function (obj) {
                0000
                var data = obj.data;
                console.log(data.id);
                if (obj.event === 'sortTest') {
                    layerConfirm(requireUrl.remove, {
                        id: data.id,
                    });
                } else if (obj.event === 'edit') {
                    layerOpenInit(
                        '编辑',
                        $('.J-temple'),
                        function (index) {
                            var data = $('form').serialize();
                            ajaxRequest('post', requireUrl.edit, data, function (data) {
                                data.code == 1 ? successTrip(data) : errorAlert(false, data.msg);
                            });
                        },
                        function () {
                            ajaxRequest(
                                'get',
                                requireUrl.edit,
                                {
                                    id: data.id,
                                },
                                function (res) {
                                    listenRole();
                                    form.val('formTest', res.data);
                                    if (res.data.role == 2) {
                                        $('.J-invigilate').hide();
                                    } else {
                                        $('.J-patrol-test').hide();
                                    }
                                }
                            );
                        }
                    );
                }
            });
        });
    }

    /**
     * 取出随机数, maxNum为 取出随机数的个数
     *
     **/
    function RandomNumBoth(arr, maxNum) {
        var numArr = [];
        //最大的循环次数
        var arrLength = arr.length;
        for (var i = 0; i < arrLength; i++) {
            //获取arr的长度
            var Rand = arr.length;
            //取出随机数
            var number = Math.floor(Math.random() * arr.length); //生成随机数num
            //往新建的数组里面传入数值
            numArr.push(arr[number]);
            //传入一个删除一个，避免重复
            arr.splice(number, 1);
            if (arr.length <= arrLength - maxNum) {
                return numArr;
            }
        }
    }

    // 数组分为双数组
    function sliceArrTo2(ran) {
        var arr = [];
        for (var courseIds = 0; courseIds < ran.length; courseIds += ran.length / 2) {
            arr.push(ran.slice(courseIds, courseIds + ran.length / 2));
        }
        return arr;
    };
</script>